package com.tju.welding.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.tju.welding.dao.TestMapper;
import com.tju.welding.service.TestService;
import com.tju.welding.utils.ApiResponse;
import com.tju.welding.utils.Code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import lombok.Cleanup;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    TestMapper testMapper;

    @Override
    public int getCustNum() {
        return testMapper.getCustNum();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public ApiResponse addRecord(int data, MultipartFile image) {

        String path = "/home/lighthouse/welding/images/";
        //String path = "/home/xsr/images/"; // 用于本机测试
        try {

            String temp = testMapper.getImagePath(data);
            if (temp != null) {
                return ApiResponse.error(Code.LOG_EXISTED);
            } else {
                path = path + testMapper.getCustNum() + ".png";
                image.transferTo(new File(path));
                testMapper.addRecord(data, path);
                return ApiResponse.success(path);
            }

        } catch (Exception e) {

            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);

        }

    }

    @Override
    public byte[] getImage(int data) throws IOException {

        String path = testMapper.getImagePath(data);
        @Cleanup
        FileInputStream picInput = new FileInputStream(path);
        return picInput.readAllBytes();

    }

}
